Edit and Update in Blazor
In this video we will discuss how to perform Edit and Update operation in Blazor.
EditEmployee Component Class
- In
HandleValidSubmit()
method,EmployeeService.UpdateEmployee
method updates the employee data in the underlying database by calling REST API.
NavigationManager.NavigateTo("/")
method redirects the user to the list page after a successful update.
using AutoMapper;
using EmployeeManagement.Models;
using EmployeeManagement.Web.Models;
using EmployeeManagement.Web.Services;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmployeeManagement.Web.Pages
{
public class EditEmployeeBase : ComponentBase
{
[Inject]
public IEmployeeService EmployeeService { get; set; }
private Employee Employee { get; set; } = new Employee();
public EditEmployeeModel EditEmployeeModel { get; set; } = new EditEmployeeModel();
[Inject]
public IDepartmentService DepartmentService { get; set; }
public List<Department> Departments { get; set; } = new List<Department>();
[Parameter]
public string Id { get; set; }
[Inject]
public IMapper Mapper { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
protected async override Task OnInitializedAsync()
{
Employee = await EmployeeService.GetEmployee(int.Parse(Id));
Departments = (await DepartmentService.GetDepartments()).ToList();
Mapper.Map(Employee, EditEmployeeModel);
}
protected async Task HandleValidSubmit()
{
Mapper.Map(EditEmployeeModel, Employee);
var result = await EmployeeService.UpdateEmployee(Employee);
if (result != null)
{
NavigationManager.NavigateTo("/");
}
}
}
}
EditEmployee Component - Blazor EditForm
@page "/editemployee/{id}"
@inherits EditEmployeeBase
<EditForm Model="@EditEmployeeModel" OnValidSubmit="HandleValidSubmit">
<ObjectGraphDataAnnotationsValidator />
<h3>Edit Employee</h3>
<hr />
<ValidationSummary />
<div class="form-group row">
<label for="firstName" class="col-sm-2 col-form-label">
First Name
</label>
<div class="col-sm-10">
<InputText id="firstName" class="form-control" placeholder="First Name"
@bind-Value="EditEmployeeModel.FirstName" />
<ValidationMessage For="@(() => EditEmployeeModel.FirstName)" />
</div>
</div>
<div class="form-group row">
<label for="lastName" class="col-sm-2 col-form-label">
Last Name
</label>
<div class="col-sm-10">
<InputText id="lastName" class="form-control" placeholder="Last Name"
@bind-Value="EditEmployeeModel.LastName" />
<ValidationMessage For="@(() => EditEmployeeModel.LastName)" />
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">
Email
</label>
<div class="col-sm-10">
<InputText id="email" class="form-control" placeholder="Email"
@bind-Value="EditEmployeeModel.Email" />
<ValidationMessage For="@(() => EditEmployeeModel.Email)" />
</div>
</div>
<div class="form-group row">
<label for="confirmEmail" class="col-sm-2 col-form-label">
Confirm Email
</label>
<div class="col-sm-10">
<InputText id="confirmEmail" class="form-control"
@bind-Value="EditEmployeeModel.ConfirmEmail" />
<ValidationMessage For="@(() => EditEmployeeModel.ConfirmEmail)" />
</div>
</div>
<div class="form-group row">
<label for="department" class="col-sm-2 col-form-label">
Department
</label>
<div class="col-sm-10">
<CustomInputSelect @bind-Value="EditEmployeeModel.DepartmentId" class="form-control">
@foreach (var dept in Departments)
{
<option value="@dept.DepartmentId">@dept.DepartmentName</option>
}
</CustomInputSelect>
</div>
</div>
<div class="form-group row">
<label for="gender" class="col-sm-2 col-form-label">
Gender
</label>
<div class="col-sm-10">
<InputSelect @bind-Value="EditEmployeeModel.Gender" class="form-control">
@foreach (var gender in Enum.GetValues(typeof(Gender)))
{
<option value="@gender">@gender</option>
}
</InputSelect>
</div>
</div>
<div class="form-group row">
<label for="dateOfBirth" class="col-sm-2 col-form-label">
Date Of Birth
</label>
<div class="col-sm-10">
<InputDate @bind-Value="EditEmployeeModel.DateOfBrith" class="form-control" />
</div>
</div>
@*<div class="form-group row">
Updating Department Name from this page does not make sense
This is only here to demonstrate complex model validation
<label for="deptName" class="col-sm-2 col-form-label">
Department Name
</label>
<div id="deptName" class="col-sm-10">
<InputText @bind-Value="EditEmployeeModel.Department.DepartmentName"
class="form-control" />
<ValidationMessage For="@(() => EditEmployeeModel.Department.DepartmentName)" />
</div>
</div>*@
<button class="btn btn-primary" type="submit">Submit</button>
</EditForm>
IEmployeeService
public interface IEmployeeService
{
Task<IEnumerable<Employee>> GetEmployees();
Task<Employee> GetEmployee(int id);
Task<Employee> UpdateEmployee(Employee updatedEmployee);
}
EmployeeService
using EmployeeManagement.Models;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace EmployeeManagement.Web.Services
{
public class EmployeeService : IEmployeeService
{
private readonly HttpClient httpClient;
public EmployeeService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<Employee> GetEmployee(int id)
{
return await httpClient.GetJsonAsync<Employee>($"api/employees/{id}");
}
public async Task<IEnumerable<Employee>> GetEmployees()
{
return await httpClient.GetJsonAsync<Employee[]>("api/employees");
}
public async Task<Employee> UpdateEmployee(Employee updatedEmployee)
{
return await httpClient.PutJsonAsync<Employee>("api/employees", updatedEmployee);
}
}
}
REST API UpdateEmployee Method
public async Task<ActionResult<Employee>> UpdateEmployee(Employee employee)
{
try
{
var employeeToUpdate = await employeeRepository.GetEmployee(id);
if(employeeToUpdate == null)
{
return NotFound($"Employee with Id = {id} not found");
}
return await employeeRepository.UpdateEmployee(employee);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error updating data");
}
}
© 2020 Pragimtech. All Rights Reserved.